package cn.akaba.java_first_web;

import javax.servlet.*;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

public class TestServlet implements Servlet {

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println(servletConfig.toString());
        System.out.println("init --- on");
    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("servlet service");
        System.out.println("request " + servletRequest.getRemoteHost() + "]: local[" + servletRequest.getLocalAddr());
        System.out.println("request search@name : " + servletRequest.getParameter("name"));
        PrintWriter writer = servletResponse.getWriter();
        final String htmlFile = "/Users/chiyuxinyi/Documents/procedures/js_zgc/src/views/Home/Home.html";
        FileReader fileReader = new FileReader(htmlFile);
        int num = fileReader.read();
        StringBuilder data = new StringBuilder();
        while(num >= 0) {
            data.append(String.valueOf((char) num));
            num = fileReader.read();
        }
        data.append('&');
        servletResponse.setContentType("text/html");
        writer.println("<div><code><pre>" + String.valueOf(data).replace("&", "&amp;").replace("<", "&lt;").replace(">","&gt;") + "</pre></code></div>");
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {
        System.out.println("servlet destroy");
    }
}
